import { createSlice } from "@reduxjs/toolkit";


const initialState: { value: any } = {
  value: {
    current: 0,
    menus: [
      { name: '聊天', type: 'icon-duihua', path: '/chat', num: 0 },
      { name: '好友', type: 'icon-yonghu', path: '/friend', num: 0 },
      { name: '群聊', type: 'icon-qunliao', path: '/group', num: 0 },
      { name: '收藏', type: 'icon-shoucang', path: '/collection', num: 0 },
    ]
  },
};

try {
  const current = localStorage.getItem("current");
  if (current !== null) {
    initialState.value.current = parseInt(current);
  }
} catch (error) {
  console.error('Error initializing user state:', error);
}



export const menusSlice = createSlice({
  name: "menus",
  initialState,
  reducers: {
    setCurrent: (state, action) => {
      localStorage.setItem('current', `${action.payload}`)
      state.value.current = action.payload;
    },
    updateMenusNum: (state, action) => {
      const { name, num } = action.payload;

      state.value.menus =   state.value.menus.map((item: any) => {
        if (item.name == name) {
          item.num = num;
        }
        return item;
      })
    }
  },
})

export const { setCurrent,updateMenusNum } = menusSlice.actions;

export default menusSlice.reducer